package com.dlc.apk.utils;

import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.dlc.apk.receiver.NetworkChangeReceiver;

public class NetworkUtil {
    private static NetworkChangeReceiver networkChangeReceiver;
    private static boolean mReceiverTag = false;   //广播接受者标识

    //代码中动态注册广播
    public static void registerReceiver(Context context) {
        if (!mReceiverTag) {     //在注册广播接受者的时候 判断是否已被注册,避免重复多次注册广播
            mReceiverTag = true;
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
            networkChangeReceiver = new NetworkChangeReceiver();
            context.registerReceiver(networkChangeReceiver, intentFilter);
        }
    }

    //注销广播
    public static void unregisterReceiver(Context context) {
        if (mReceiverTag) {   //判断广播是否注册
            mReceiverTag = false;   //Tag值 赋值为false 表示该广播已被注销
            context.unregisterReceiver(networkChangeReceiver);   //注销广播
        }

    }

    /**
     * 判断是否打开网络
     *
     * @param context
     * @return
     */
    public static boolean isNetWorkAvailable(Context context) {
        boolean isAvailable = false;
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isAvailable()) {
            isAvailable = true;
        }
        return isAvailable;
    }
}
